<template>
  <div class="login"
       :style="{background: 'url('+bgimgBtn+')',backgroundRepeat: 'no-repeat',backgroundSize:'cover'}">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">小森林智慧校园</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          autocomplete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          prefix-icon="el-icon-lock"
          v-model="loginForm.password"
          type="text"
          name="pwd"
          id="pwd"
          placeholder="密码"
          autocomplete="off"
          @input="setPassword">
          <i slot="suffix" class="el-icon-view" @click="hidePassword"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <div class="qrcode-line-box">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            autocomplete="off"
            placeholder="验证码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </div>
      </el-form-item>
      <!--      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>-->
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2023 xiaosenlin All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import bgimgBtn from '@/assets/imageAdmin/bgcont.jpg'
import { getCodeImg } from '@/api/login'

export default {
  name: "Login",
  data() {
    return {
      bgimgBtn: bgimgBtn,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      isShowPassword: false,
      password: ''
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    // this.getCookie();
  },
  methods: {
    setPassword(val) {
      if (this.isShowPassword) {
        this.loginForm.password = val;
        this.password = val
      } else {
        let nDot = /[^●]/g; // 非圆点字符
        let index = -1; // 新输入的字符位置
        let lastChar = void 0; // 新输入的字符
        let realArr = this.password.split(""); // 真实密码数组
        let coverArr = val.split(""); // 文本框显示密码数组
        let coverLen = val.length; // 文本框字符串长度
        let realLen = this.password.length; // 真实密码长度
        // 找到新输入的字符及位置
        coverArr.forEach((el, idx) => {
          if (nDot.test(el)) {
            index = idx;
            lastChar = el;
          }
        });
        if (coverLen - 1 !== realLen) {
          // 一进入长度判断是否复制
          // 其中会发生如果先输入，后复制会有前面数字为圆点
          realArr = coverArr
        } else {
          if (realLen < coverLen) {
            // 新增字符
            realArr.splice(index, 0, lastChar);
          } else if (coverLen <= realLen && index !== -1) {
            // 替换字符（选取一个或多个字符直接替换）
            realArr.splice(index, realLen - (coverLen - 1), lastChar);
          } else {
            // 删除字符，因为 val 全是 ● ，没有办法匹配，不知道是从末尾还是中间删除的字符，删除了几个，不好对 password 处理，所以可以通过光标的位置和 val 的长度来判断
            let pos = document.getElementById("pwd").selectionEnd; // 获取光标位置
            realArr.splice(pos, realLen - coverLen);
          }
        }
        // 将 pwdCover 替换成 ●
        this.loginForm.password = val.replace(/\S/g, "●");
        this.password = realArr.join("");
      }
    },
    // 点击右侧小眼睛控制显示隐藏
    hidePassword() {
      if (!this.isShowPassword) {
        // console.log("显示");
        this.isShowPassword = true;
        this.loginForm.password = this.password;
      } else {
        // console.log("隐藏");
        this.isShowPassword = false;
        this.loginForm.password = this.loginForm.password.replace(/\S/g, "●");
      }
    },
    getCode() {
      // 使用与项目其他API一致的调用方式
      getCodeImg().then(res => {
        if (res.code === 200) {
          this.codeUrl = 'data:image/gif;base64,' + res.img;
          this.loginForm.uuid = res.uuid;
        }
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        let regex = /^#[\w\d]+$/; // 示例正则表达式，用于匹配以#开头的字母、数字字符
        let is_can_login = true
        if (regex.test(this.loginForm.username)) {
          // 如果正则表达式匹配成功，设置location.hash
          location.hash = this.loginForm.username;
          is_can_login = false
        } else {
          // 如果不匹配，给出错误处理或提示
          console.log("Invalid hash provided.");
        }
        if (valid && is_can_login) {
          this.loading = true;
          let data_ = JSON.parse(JSON.stringify(this.loginForm))
          data_.password = this.password
          this.$store.dispatch("Login", data_).then((res) => {
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
            if (!res) {
              // this.$message.error('登入失败')
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            }
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  //width: 33%;
  height: 38px;
  //float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
    height: 38px;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  //height: 38px;
}

.qrcode-line-box {
  display: flex;
  align-items: center;
}

.qrcode-line-box .el-input {
  width: 198px;
  margin-right: 10px;
}
</style>
